package com.androidcourse.shounews.Fragment;

import static android.content.ContentValues.TAG;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;

import com.androidcourse.shounews.Activity.MainActivity;
import com.androidcourse.shounews.Adapter.CommonNewsAdapter;
import com.androidcourse.shounews.Adapter.LinksAdapter;
import com.androidcourse.shounews.Adapter.MyNewsAdapter;
import com.androidcourse.shounews.Adapter.NewsTopAdapter;
import com.androidcourse.shounews.Entity.CommonNews;
import com.androidcourse.shounews.Entity.MyNews;
import com.androidcourse.shounews.HttpUtil.NewsHttp;
import com.androidcourse.shounews.MyDialog.MyDialog;
import com.androidcourse.shounews.MyDialog.MyDialog1;
import com.androidcourse.shounews.R;
import com.androidcourse.shounews.SqlLite.MyDBHelper;
import com.androidcourse.shounews.Toast.MyCustomToast;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link FirstFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class FirstFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener, NewsTopAdapter.OnItemClickListener, CommonNewsAdapter.OnItemClickListener, View.OnClickListener, MyNewsAdapter.OnItemClickListener, LinksAdapter.OnItemClickListener {
    private RecyclerView recyclerView_news;
    private RecyclerView recyclerView_top;
    private RecyclerView recyclerView_my_news;
    private RecyclerView recyclerView_links;
    private CommonNewsAdapter commonNewsAdapter;
    private NewsTopAdapter newsTopAdapter;
    private MyNewsAdapter myNewsAdapter;
    private LinksAdapter linksAdapter;
    private List<CommonNews> commonNewsList=new ArrayList<>();
    private List<String> topList=new ArrayList<>();
    private List<MyNews> myNewsList =new ArrayList<>();
    private List<MyNews> linkList=new ArrayList<>();
    private SwipeRefreshLayout refreshLayout;
    private ImageButton imageRefresh;
    private Handler handler;
    private MyDBHelper myDBHelper;

    private SharedPreferences preferences;
    private int selectedTop=-1;
    private boolean isInit=false;
    private final int ERROR=-1;
    private final int CHECK= 1;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        initHandler();
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false);
    }
    //创建myDBHelper实例
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        myDBHelper=MyDBHelper.getInstance(getContext());
        myDBHelper.getRead();
        myDBHelper.getWrite();
        preferences=getActivity().getSharedPreferences("count", Context.MODE_PRIVATE);
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        recyclerView_news=getActivity().findViewById(R.id.news_recycle_view_list);
        recyclerView_top=getActivity().findViewById(R.id.news_recycle_view_list_top);
        recyclerView_my_news =getActivity().findViewById(R.id.my_news_recycle_view_list);
        recyclerView_links =getActivity().findViewById(R.id.link_recycle_view_list);
        refreshLayout=getActivity().findViewById(R.id.news_recycle_view_list_refresh);
        imageRefresh=getActivity().findViewById(R.id.refresh_top_list);
        imageRefresh.setOnClickListener(this);
        ImageButton imageButton=getActivity().findViewById(R.id.refresh_my_news_list);
        imageButton.setOnClickListener(this);
        refreshLayout.setOnRefreshListener(this);
        if(!isInit){
            initList();
        }
        checkNew();
        initRecyclerView();
    }
    private void initRecyclerView(){
        RecyclerView.LayoutManager layoutManager1=new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false);
        recyclerView_news.setLayoutManager(layoutManager1);
        commonNewsAdapter=new CommonNewsAdapter(commonNewsList,this);
        recyclerView_news.setAdapter(commonNewsAdapter);
        RecyclerView.LayoutManager layoutManager2=new LinearLayoutManager(getContext(),LinearLayoutManager.HORIZONTAL,false);
        recyclerView_top.setLayoutManager(layoutManager2);
        newsTopAdapter=new NewsTopAdapter(topList,this);
        recyclerView_top.setAdapter(newsTopAdapter);
        RecyclerView.LayoutManager layoutManager3=new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false);
        myNewsAdapter =new MyNewsAdapter(myNewsList,this);
        recyclerView_my_news.setLayoutManager(layoutManager3);
        recyclerView_my_news.setAdapter(myNewsAdapter);
        RecyclerView.LayoutManager layoutManager4=new LinearLayoutManager(getContext(),LinearLayoutManager.VERTICAL,false);
        linksAdapter =new LinksAdapter(linkList,this);
        recyclerView_links.setLayoutManager(layoutManager4);
        recyclerView_links.setAdapter(linksAdapter);
    }
    private void initList(){
        updateTopList();
        updateMyNewsList();
        updateLinksList();
    }
    private void initHandler(){
        this.handler=new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                int id=msg.what;
                if(id==ERROR) new MyCustomToast(getContext(),R.drawable.toast_error_24,"更新失败!");
                if(id==R.id.news_recycle_view_list_top){
                    //topList更新
                    topList.clear();
                    topList.addAll ((List<String>) msg.obj);
                    if(!topList.isEmpty()&&!isInit){
                        updateNewsList(topList.get(0).toString());
                        isInit=true;
                    }
                    newsTopAdapter.notifyDataSetChanged();
                    recyclerView_top.invalidate();
                }
                else if(id==R.id.news_recycle_view_list){
                    //commonNewsList更新
                    commonNewsList.clear();
                    commonNewsList.addAll((List<CommonNews>)msg.obj);
                    commonNewsAdapter.notifyDataSetChanged();
                    recyclerView_news.invalidate();
                }
                else if(id==R.id.link_recycle_view_list){
                    List<MyNews> myNews= (List<MyNews>) msg.obj;
                    //linkList更新
                    linkList.clear();
                    linkList.addAll(myNews);
                    linksAdapter.notifyDataSetChanged();
                    recyclerView_links.invalidate();
                }
                else if(id==CHECK){
                    int count=preferences.getInt("count",-1);
                    Log.d(TAG, "handleMessage: "+count);
                    if(count<(int)msg.obj){
                        MyDialog myDialog=new MyDialog(getContext());
                        myDialog.setsMessage("有新的文章发布!").setsConfirm("确定", new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                myDialog.dismiss();
                            }
                        }).show();
                    }
                    SharedPreferences.Editor editor= preferences.edit();
                    editor.putInt("count",(int)msg.obj);
                    editor.apply();
                }
            }
        };
    }
    @Override
    public void onRefresh() {
        if(selectedTop!=-1){
            updateNewsList(topList.get(selectedTop));
        }
        new MyCustomToast(getContext(),MyCustomToast.SUCCESS,"刷新成功");
        refreshLayout.setRefreshing(false);
    }
    /**
     * 点击top的item时刷新下面
     * @param position 点击的位置
     */
    @Override
    public void onTopItemClick(int position) {
        //更新当前选择的索引
        selectedTop=position;
        //更新commonNewsList
        updateNewsList(topList.get(position));
    }
    /**
     * 点击news时的item时跳转页面
     * @param position
     */
    @Override
    public void onNewsItemClick(int position) {
        //跳转至新闻页
        Bundle bundle=new Bundle();
        bundle.putString("title",commonNewsList.get(position).getTitle());
        //bundle.putString("contentUrl","https://www.csdn.net/");
        bundle.putString("contentUrl",commonNewsList.get(position).getContentUrl());
        ((MainActivity)getActivity()).openWebFragment(bundle);
    }
    @Override
    public void OnLinkItemClick(int position) {
        Log.d(TAG, "OnMyNewsItemClick: ");
        //跳转至新闻页
        Bundle bundle=new Bundle();
        bundle.putString("title",linkList.get(position).getName());
//        bundle.putString("contentUrl","https://www.csdn.net/");
        bundle.putString("contentUrl",linkList.get(position).getLink());
        ((MainActivity)getActivity()).openWebFragment(bundle);
    }

    @Override
    public void OnMyNewsItemClick(int position) {
        Log.d(TAG, "OnMyNewsItemClick: ");
        //跳转至新闻页
        Bundle bundle=new Bundle();
        bundle.putString("title",myNewsList.get(position).getName());
//        bundle.putString("contentUrl","https://www.csdn.net/");
        bundle.putString("contentUrl",myNewsList.get(position).getLink());
        ((MainActivity)getActivity()).openWebFragment(bundle);
    }

    @Override
    public void OnMyNewsItemLongClick(int position) {
        Log.d(TAG, "OnMyNewsItemLongClick: "+position);
        MyDialog1 myDialog=new MyDialog1(getContext());
        myDialog.setsTitle("警告").setsMessage("确定要删除吗？")
                .setsCancel("取消", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        myDialog.dismiss();
                    }
                }).setsConfirm("确定", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(myDBHelper.deleteByName(myNewsList.get(position).getName())) {
                            new MyCustomToast(getContext(), MyCustomToast.SUCCESS, "删除成功!");
                            myDialog.dismiss();
                        }
                        else {
                            new MyCustomToast(getContext(),MyCustomToast.ERROR,"删除失败");
                            myDialog.dismiss();
                            return;
                        }
                        myNewsList.remove(position);
                        myNewsAdapter.notifyItemChanged(position);
                    }
                }).show();
    }

    @Override
    public void onClick(View v) {
        int id=v.getId();
        if(id==R.id.refresh_top_list){
            updateTopList();
            new MyCustomToast(getContext(),MyCustomToast.SUCCESS,"刷新成功");
        }else if(id==R.id.refresh_my_news_list){
            updateMyNewsList();
            myNewsAdapter.notifyDataSetChanged();
            new MyCustomToast(getContext(),MyCustomToast.SUCCESS,"刷新成功");
        }
    }
    /**
     * 更新topList数据
     */
    private void updateTopList(){
        //向服务端发送请求获取数据
        NewsHttp.getAllAuthorByType("wechat")
                .thenAccept(res->{
                    //通知主线程topList更新
                    Message message=handler.obtainMessage();
                    message.what=R.id.news_recycle_view_list_top;
                    message.obj=res;
                    handler.sendMessage(message);
                })
                .exceptionally(e->{
                    Log.e(TAG, "updateTopList: ", e);
                    Message message=handler.obtainMessage();
                    message.what=ERROR;
                    handler.sendMessage(message);
                    return null;
                });
    }

    /**
     * @param author 作者名
     */
    private void updateNewsList(String author){
        NewsHttp.getAllNewsByAuthor(author)
                .thenAccept(res->{
                    //通知主线程
                    Message message=handler.obtainMessage();
                    message.what=R.id.news_recycle_view_list;
                    message.obj=res;
                    handler.sendMessage(message);
                })
                .exceptionally(e->{
                    Log.e(TAG, "updateNewsList: ", e);
                    Message message=handler.obtainMessage();
                    message.what=ERROR;
                    handler.sendMessage(message);
                    return null;
                });
    }

    /**
     * 更新常用链接
     */
    public void updateLinksList(){
        NewsHttp.getAllLink()
                .thenAccept(res->{
                    //通知主线程
                    Message message=handler.obtainMessage();
                    message.what=R.id.link_recycle_view_list;
                    message.obj=res;
                    handler.sendMessage(message);
                })
                .exceptionally(e->{
                    Log.e(TAG, "updateLinksList: ", e);
                    Message message=handler.obtainMessage();
                    message.what=ERROR;
                    handler.sendMessage(message);
                    return null;
                });
    }
    /**
     * 检验是否有新消息
     */
    private void checkNew(){
       NewsHttp.getAllNewsCount()
               .thenAccept(res->{
                   //通知主线程
                   Message message=handler.obtainMessage();
                   message.what=CHECK;
                   message.obj=res;
                   handler.sendMessage(message);
               })
               .exceptionally(e->{
                   Log.e(TAG, "updateLinksList: ", e);
                   Message message=handler.obtainMessage();
                   message.what=ERROR;
                   handler.sendMessage(message);
                   return null;
               });
    }
    /**
     * 更新我的新闻网址信息
     */
    private void updateMyNewsList(){
        myNewsList.clear();
        myNewsList.addAll(myDBHelper.queryAll());
    }

}